package com.lhn.netty.netty_demo.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Netty
 *
 * @author lhn
 * @date 2025/05/30 10:42
 * @since 1.0.0
 **/
public class NettyClient {

    public static void main(String[] args) {
        // 客户端需要一个时间循环组
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        // 创建客户端启动对象
        // 注意客户端不需要使用ServerBootstrap
        Bootstrap bootstrap = new Bootstrap();
        // 设置相关参数
        try {
            bootstrap.group(eventExecutors) // 设置线程组
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel作为客户端通道实现(反射)
                    .handler(new ChannelInitializer <NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            nioSocketChannel.pipeline().addLast(new NettyClientHandler()); // 加入自己的处理器
                        }
                    });
            System.out.println("client start....");
            // 启动客户端去连接服务器]
            try {
                // 关于 ChannelFuture 涉及到 Netty 的异步模型
                ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
                // 给关闭通道进行监听
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            eventExecutors.shutdownGracefully();
        }

    }

}